import 'package:badges/badges.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:gim_plugin/gim_plugin.dart';
import 'package:gim_plugin_example/components/empty_box.dart';
import 'package:gim_plugin_example/components/my_appbar.dart';
import 'package:gim_plugin_example/components/my_img.dart';
import 'package:gim_plugin_example/global.dart';
import 'package:gim_plugin_example/pages/pg_chat_room/pg_chat_room.dart';
import 'package:gim_plugin_example/pages/tab_conversation/tab_conversation_store.dart';
import 'package:gim_plugin_example/sdk/gim_sdk.dart';
import 'package:gim_plugin_example/utils/date_utils.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:provider/provider.dart';

import '../../app_nav.dart';
import '../../icons.dart';
import '../../std.dart';

class TabConversation extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _TabConversationState();
}

class _TabConversationState extends State<TabConversation> {
  String? avatar;
  late String myUid;

  @override
  void initState() {
    gimSdk.gim.addConversationUpdateFn(onConversationUpdate);
    Global global = context.read<Global>();
    myUid = global.uid!;
    Future.delayed(Duration.zero).then((_) {
      TabConversationStore store = context.read<TabConversationStore>();
      if (store.list.isEmpty) {
        store.getList(refresh: true);
      }
    });
    super.initState();
  }

  void onConversationUpdate(ConversationInfo info) {
    TabConversationStore store = context.read<TabConversationStore>();
    store.updateListIndex(info);
  }

  @override
  void dispose() {
    gimSdk.gim.delConversationUpdateFn(onConversationUpdate);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: myAppBar('消息'),
      body: Consumer(
        builder: (BuildContext context, TabConversationStore store, Widget? child) {
          return EasyRefresh.custom(
              cacheExtent: 40,
              enableControlFinishRefresh: false,
              enableControlFinishLoad: false,
              header: CustomHeader(headerBuilder: (BuildContext context,
                  RefreshMode refreshState,
                  double pulledExtent,
                  double refreshTriggerPullDistance,
                  double refreshIndicatorExtent,
                  AxisDirection axisDirection,
                  bool float,
                  Duration? completeDuration,
                  bool enableInfiniteRefresh,
                  bool success,
                  bool noMore) {
                return Center(
                  child: LoadingAnimationWidget.fallingDot(color: themeColor, size: 50),
                );
              }),
              footer: CustomFooter(footerBuilder: (BuildContext context,
                  LoadMode loadState,
                  double pulledExtent,
                  double loadTriggerPullDistance,
                  double loadIndicatorExtent,
                  AxisDirection axisDirection,
                  bool float,
                  Duration? completeDuration,
                  bool enableInfiniteLoad,
                  bool success,
                  bool noMore) {
                return Center(
                  child: LoadingAnimationWidget.prograssiveDots(color: themeColor, size: 50),
                );
              }),
              onRefresh: () async {
                store.getList(refresh: true);
              },
              onLoad: () async {
                store.getList(refresh: false);
              },
              slivers: [
                store.list.isNotEmpty
                    ? buildConvList(list: store.list, onback: () {})
                    : SliverToBoxAdapter(
                  child: EmptyBox(tip: '暂无消息'),
                )
              ]);
        },
      ),
    );
  }


  SliverList buildConvList({required List<ConversationInfo> list, VoidCallback? onback}) {
    return SliverList(
      delegate: SliverChildBuilderDelegate((context, index) {
        return Slidable(
            key: ValueKey('Slidable-${list[index].id}'),
            endActionPane: ActionPane(
              extentRatio: 68 / windowWidth,
              motion: const ScrollMotion(),
              children: [
                CupertinoButton(
                  padding: const EdgeInsets.only(left: 20, right: 20, top: 28, bottom: 28),
                  onPressed: () {
                    TabConversation store = context.read<TabConversation>();
                    // store.delConv(convId: list[index].convId!);
                  },
                  borderRadius: BorderRadius.circular(0),
                  color: const Color(0xFFF8335E),
                  child: text14('删除', color: Colors.white),
                )
              ],
            ),
            child: _buildConvItem(context, item: list[index], onback: onback));
      }, childCount: list.length),
    );
  }

  Widget _buildConvItem(BuildContext context, {required ConversationInfo item, VoidCallback? onback}) {
    Widget? sendIndicator;
    if (item.lastMsg != null) {
      var lastMsg = item.lastMsg!;
      if (lastMsg.code == null) {
        sendIndicator = iconSending(14);
      } else if (lastMsg.code == 0) {
        if (myUid == lastMsg.fromUid) {
          sendIndicator = iconWaitReply(14);
        }
      } else {
        sendIndicator = iconSendErr(14);
      }
    }

    return MaterialButton(
      onPressed: () async {
        AppNav.of(context).push(PgChatRoom(remoteUid: item.toUid!, remoteNickname: item.nickname!, remoteAvatar: item.avatar!));

      },
      key: Key('${item.id}'),
      minWidth: windowWidth,
      color: Colors.white,
      elevation: 0,
      hoverElevation: 0,
      highlightElevation: 0,
      splashColor: const Color.fromRGBO(34, 34, 34, 0.1),
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
      padding: EdgeInsets.only(left: pgPadding, right: pgPadding, top: 10, bottom: 10),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Badge(
            elevation: 0,
            showBadge: (item.unreadCount ?? 0) > 0,
            shape: BadgeShape.square,
            padding: const EdgeInsets.only(left: 5, right: 5, top: 2, bottom: 2),
            borderRadius: const BorderRadius.only(
                topRight: Radius.circular(10), topLeft: Radius.circular(10), bottomRight: Radius.circular(10)),
            position: BadgePosition.topEnd(top: -7, end: item.unreadCount! < 10 ? -5 : -10),
            badgeContent: Text(item.unreadCount! <= 99 ? '${item.unreadCount!}' : '99+',
                style: const TextStyle(fontSize: 10, color: Colors.white)),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(25),
              child: myImg(item.avatar!, width: 50, height: 50),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text.rich(TextSpan(children: [
                        TextSpan(
                            text: item.nickname!,
                            style: TextStyle(fontSize: font16, fontWeight: FontWeight.w600, color: blackColor)),
                        // WidgetSpan(
                        //     child: Offstage(
                        //       offstage: !isTrue(item.online),
                        //       child: Container(
                        //         padding: const EdgeInsets.only(left: 5, right: 5, top: 3, bottom: 3),
                        //         margin: const EdgeInsets.only(left: 5),
                        //         decoration: BoxDecoration(
                        //           color: const Color.fromRGBO(0, 204, 184, 0.1),
                        //           borderRadius: BorderRadius.circular(10),
                        //         ),
                        //         child: text10('在线', color: const Color(0xFF00CCB8), fontWeight: FontWeight.w600),
                        //       ),
                        //     ))
                      ])),
                      Offstage(
                        offstage: item.lastMsg == null,
                        child: text12(diffCurrent(DateTime.fromMillisecondsSinceEpoch((item.createdAt ?? 0) * 1000)),
                            color: const Color(0xFF999999)),
                      )
                    ],
                  ),
                  const SizedBox(height: 10),
                  SizedBox(
                    width: double.infinity,
                    height: 24,
                    child: Row(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Offstage(
                          offstage: sendIndicator == null,
                          child: Padding(padding: const EdgeInsets.only(right: 4), child: sendIndicator),
                        ),
                        Expanded(
                            child: textDot(_parseLastMsg(item.lastMsg), fontSize: font12, color: const Color(0xFF999999))),
                      ],
                    ),
                  )
                ],
              ))
        ],
      ),
    );
  }

  String _parseLastMsg(C2cMsg? msg) {
    if (msg == null) return '';
    if (msg.msgType == MsgTypes.MsgTypeText) {
      return msg.msgData ?? '';
    } else if (msg.msgType == MsgTypes.MsgTypeAudio) {
      return '[语音]';
    } else if (msg.msgType == MsgTypes.MsgTypeImage) {
      return '[图片]';
    } else if (msg.msgType == MsgTypes.MsgTypeVideo) {
      return '[视频]';
    } else if (msg.msgType == MsgTypes.MsgTypeGeo) {
      return '[地理位置]';
    } else {
      return '[自定义消息]';
    }
  }

}